<?php
class ControleAdmin extends Control
{
	public function index()
	{
		$this->setLayout('admin');

		$item = new Item();
		$items = $item->search(null, array('status' => ' = 1'));

		$this->view->assign('items', $items);

		return $this->view;
	}

	public function adminLista()
	{
		$lista = new Lista();
		$listas = $lista->search();

		$this->view->assign('listas', $listas);

		$this->setTemplate('lista');
		return $this->view;
	}

	public function salvarLista()
	{
		$lista = new Lista();
		if(isset($this->params['id']) && !empty($this->params['id']))
			$lista->load($this->params['id']);

		$lista->nome = $this->params['nome'];
		$lista->save();

		echo $lista->toJSON();
	}

	public function adminItemLista()
	{
		$this->setTemplate('formItem');

		$lista = new Lista();
		$listas = $lista->search();

		$this->view->assign('listas', $listas);
		return $this->view;
	}

	public function salvarItemLista()
	{
		$item = new Item();
		$item->nome = $this->params['nome'];
		$item->valor = $this->params['valor'];
		$item->id_lista = $this->params['id_lista'];
		$item->save();

		echo $item->toJSON();
	}

	public function carregarItemLista()
	{
		$item = new Item();
		$items = $item->search(null, array('id_lista' => ' = ' . $this->params['id_lista']));

		return json_encode($items);
	}

	public function planilha()
	{
		return $this->view;
	}

	public function importar()
	{
		require_once 'excel_reader2.php';

		$arquivo = ControleURI::$file['arquivo'];
		$nome = Util::removerCaracter($arquivo['name']);

		if(move_uploaded_file($arquivo['tmp_name'], 'public/uploads/'.$nome))
		{
			$data = new Spreadsheet_Excel_Reader('public/uploads/'.$nome, false,'UTF-8');
			$totalLinhas = $data->rowcount();
			$totalColunas= $data->colcount();

			for($i = 1; $i <= $totalLinhas; $i++){
				for($j = 1; $j <= $totalColunas; $j++){
					$a[$i][$j] = $data->val($i,$j);
				}
			}

			if(count($a))
			{
				POPEnvironment::$debug = true;
				$id_lista = $data->val('1','1');
				$item = new Item();
				$item->dropTable();
				$item->createTable();

				foreach($a as $key => $items)
				{
					if($key != "1")
					{
						$item = new Item();
						$item->id_lista = $id_lista;
						$item->nome = strtoupper($items['1']);
						$item->valor = (isset($items['2']))? $items['2'] : 0.0;
						$item->status = 0;
						$item->save();
					}
				}
			}
		}
	}
}